package pocker;

import pocker.exceptions.OutOfCardsException;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * User: gia
 * Date: 23.08.2012
 * Time: 13:55
 */
public class ShuffleFirstDealer implements IDealer {

    public static final int MIN_INTERCHANGE_NUMBER = 100;
    public static final int MAX_INTERCHANGE_NUMBER = 300;
    List<Integer> pack;
    public static final int CARDS_NO = 13, DUPLICATE_NO = 4;
    public static final int TOTAL_CARDS = CARDS_NO * DUPLICATE_NO;

    public ShuffleFirstDealer() {
        pack = getCardsPack();
    }

    public int deal() throws OutOfCardsException {
        int result;

        if (pack == null || pack.size() == 0)
            throw new OutOfCardsException("No more cards in dealer pack.");

        result = pack.get(0);
        pack.remove(0);

        return result;

    }

    private List<Integer> getCardsPack() {

        return shufflePack(getOrderedPack());
    }

    private List<Integer> shufflePack(List<Integer> orderedPack) {

        Random random = new Random();
        int interchangeNumber = random.nextInt(MAX_INTERCHANGE_NUMBER - MIN_INTERCHANGE_NUMBER) + MIN_INTERCHANGE_NUMBER;

        for (int i = 0; i < interchangeNumber; i++) {
            interchangeElements(orderedPack, getRandomPosition(), getRandomPosition());
        }

        return orderedPack;
    }

    private void interchangeElements(List<Integer> orderedPack, int randomPosition1, int randomPosition2) {
        int aux = orderedPack.get(randomPosition1);
        orderedPack.set(randomPosition1, orderedPack.get(randomPosition2));
        orderedPack.set(randomPosition2, aux);

    }

    private int getRandomPosition() {
        Random random = new Random();
        return random.nextInt(TOTAL_CARDS);
    }

    private List<Integer> getOrderedPack() {
        List<Integer> result = new ArrayList<Integer>();
        for (int i = 0; i < CARDS_NO; i++) {
            for (int j = 0; j < DUPLICATE_NO; j++) {
                result.add(i + 2);
            }
        }

        return result;
    }
}
